package com.sky.controller.admin;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.MyselfLoginDTO;
import com.sky.dto.MyselfRegisterDTO;
import com.sky.entity.Myself;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.MyselfService;
import com.sky.utils.JwtUtil;
import com.sky.vo.MyselfInfoVO;
import com.sky.vo.MyselfLoginVO;
import com.sky.vo.MyselfRegisterVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@Tag(name = "管理员相关接口")
@RequestMapping("/admin/myself")
public class MyselfController {


    private final MyselfService myselfService;

    private final JwtProperties jwtProperties;

    @Autowired
    public MyselfController(MyselfService myselfService, JwtProperties jwtProperties) {
        this.myselfService = myselfService;
        this.jwtProperties = jwtProperties;
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result<MyselfRegisterVO> register(@ModelAttribute MyselfRegisterDTO myselfRegisterDTO) {
        log.info("用户注册：{}", myselfRegisterDTO);
        MyselfRegisterVO myselfLoginVO = myselfService.register(myselfRegisterDTO);
        return Result.success(myselfLoginVO);
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<MyselfLoginVO> login(@RequestBody MyselfLoginDTO myselfLoginDTO) {


        log.info("用户登录：{}", myselfLoginDTO);

        //调用service层登录方法，返回用户信息
        Myself myself = myselfService.login(myselfLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        //添加管理员id进jwt
        claims.put(JwtClaimsConstant.EMP_ID, myself.getId());
        //添加root权限进jwt
        claims.put(JwtClaimsConstant.ROOT, myself.getRoot());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        MyselfLoginVO employeeLoginVO = MyselfLoginVO.builder()
                .id(myself.getId())
                .userName(myself.getUsername())
                .name(myself.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 直接获取我的信息
     */
    @GetMapping("/getMyInfo")
    @Operation(summary = "获取我的信息")
    public Result<MyselfInfoVO> getMyInfo() {
        log.info("获取我的信息");
        MyselfInfoVO myselfInfoVO = myselfService.getMyInfo();
        return Result.success(myselfInfoVO);
    }
}
